package com.ja.openchat.ui.chat.group.adapter;

import android.graphics.drawable.Drawable;
import android.graphics.drawable.PictureDrawable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.GridSpanSizeLookup;
import com.chad.library.adapter.base.module.BaseLoadMoreModule;
import com.chad.library.adapter.base.module.LoadMoreModule;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.ja.openchat.R;
import com.ja.openchat.ui.chat.group.JsoupTaskCallback;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.model.file.DocumentInfo;
import com.zy.openchat.core.model.message.HtmlDocumentInfo;
import com.zy.openchat.core.model.message.MessageContent;
import com.zy.openchat.core.model.message.MessageInfo;
import com.zy.openchat.core.model.message.TextEntity;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.util.Common;
import com.zy.openchat.util.TimeConvertUtils;
import com.zy.openchat.util.TimeUtils;
import com.zy.openchat.util.glide.SvgSoftwareLayerSetter;

import org.jetbrains.annotations.NotNull;

public class GroupSettingChildAdapter extends BaseMultiItemQuickAdapter<MessageInfo, BaseViewHolder> implements LoadMoreModule {

    public GroupSettingChildAdapter() {
        super(null);
        addItemType(TelegramManager.MessageType.MessageType_Photo.ordinal(), R.layout.item_group_setting_of_media);
        addItemType(TelegramManager.MessageType.MessageType_Video.ordinal(), R.layout.item_group_setting_of_media);
        addItemType(TelegramManager.MessageType.MessageType_Document.ordinal(),R.layout.item_group_setting_of_file);
        addItemType(TelegramManager.MessageType.MessageType_Audio.ordinal(),R.layout.item_group_setting_of_audio);
        addItemType(TelegramManager.MessageType.MessageType_Text.ordinal(),R.layout.item_group_setting_of_link);
        addItemType(TelegramManager.MessageType.MessageType_Animation.ordinal(),R.layout.item_group_setting_of_media);
        setGridSpanSizeLookup(new GridSpanSizeLookup() {
            @Override
            public int getSpanSize(@NonNull @NotNull GridLayoutManager gridLayoutManager, int viewType, int position) {
                int item_type = getItem(position).getItemType();
                if(item_type == TelegramManager.MessageType.MessageType_Document.ordinal()
                        ||item_type == TelegramManager.MessageType.MessageType_Text.ordinal()
                        ||item_type == TelegramManager.MessageType.MessageType_Audio.ordinal()){
                    return 3;
                }else{
                    return 1;
                }
            }
        });
    }

    private RequestBuilder<Drawable> thumbnailRequest;
    protected RequestOptions placeholderOptions;

    @Override
    protected void convert(@NotNull BaseViewHolder helper, MessageInfo message) {
        if(message==null||message.content==null){
            return;
        }
        if(message.messageType==TelegramManager.MessageType.MessageType_Photo||message.messageType==TelegramManager.MessageType.MessageType_Video||message.messageType==TelegramManager.MessageType.MessageType_Animation){
            TextView message_time = helper.getView(R.id.message_time);
            message_time.setVisibility(View.GONE);
            if(thumbnailRequest==null){
                thumbnailRequest = Glide
                        .with(getContext())
                        .load(R.drawable.image_chat_placeholder);
            }
            if(placeholderOptions == null){
                placeholderOptions = new RequestOptions();
                placeholderOptions.diskCacheStrategy(DiskCacheStrategy.ALL);
                placeholderOptions.centerCrop();
                placeholderOptions.placeholder(R.drawable.image_chat_placeholder);
            }
            ImageView image_view = helper.getView(R.id.image_view);
            View gif_tag = helper.getView(R.id.gif_tag);
            gif_tag.setVisibility(View.GONE);
            String imagePath = "";
            if(message.messageType == TelegramManager.MessageType.MessageType_Photo){
                if (message.isMessagePhotoDownloaded()) {
                    imagePath = message.getMessagePhotoFile().local.path;

                }else{
                    TelegramManager.getTelegramManager().downloadFile(message.chat_id+"_" + message.id, message.getMessagePhotoFileId(), 0, TelegramManager.FileType.FileType_Message_Photo);
                }

            }else if(message.messageType == TelegramManager.MessageType.MessageType_Video){
                MessageContent videoMessageContent =  message.content;
                if(videoMessageContent!=null){
                    message_time.setVisibility(View.VISIBLE);
                    message_time.setText(TimeConvertUtils.formatLongTime(videoMessageContent.video.duration));
                    if(videoMessageContent.video.isVideoDownloaded()){
                        imagePath = videoMessageContent.video.localVideoPath();
                    }else{
                        TelegramManager.getTelegramManager().downloadFile(message.chat_id+"_" + message.id, message.getVideoFileId(), 0, TelegramManager.FileType.FileType_Message_Video);
                    }
                }
            }else if(message.messageType == TelegramManager.MessageType.MessageType_Animation){
                MessageContent videoMessageContent =  message.content;
                if(videoMessageContent!=null){
                    gif_tag.setVisibility(View.VISIBLE);
                    if (videoMessageContent.animation.isAnimationDownloaded()) {
                        imagePath = videoMessageContent.animation.localAnimationPath();
                    }else{
                        TelegramManager.getTelegramManager().downloadFile(message.chat_id+"_" + message.id, message.getAnimationFileId(), 0, TelegramManager.FileType.FileType_Message_Animation);
                    }
                }
            }
            Glide.with(getContext())
                    .load(imagePath)
                    .thumbnail(thumbnailRequest)
                    .apply(placeholderOptions)
                    .into(image_view);
        }else if(message.messageType==TelegramManager.MessageType.MessageType_Audio){
            MessageContent imageMessage = message.content;
            if(imageMessage!=null&&imageMessage.audio!=null){
                helper.setText(R.id.file_name_text, UserInfo.userDisplayName(message.sender_user_id()));
                helper.setText(R.id.file_info_text,String.format("%s   %s", imageMessage.audio.duration + "''", TimeUtils.getMsgFormatTimeYYMMDDHHMM(message.date*1000)));
            }
        }else if(message.messageType==TelegramManager.MessageType.MessageType_Text){
            HtmlDocumentInfo htmlDocumentInfo = message.getHtmlDocumentInfo();
            String content = message.textTypeContent;
            if(htmlDocumentInfo==null){
                if(message.content!=null&&message.content.text!=null&&!Common.isEmpty(message.content.text.entities)){
                    TextEntity textEntity = message.content.text.entities.get(0);
                    try {
                        content = content.substring(textEntity.start(),textEntity.end());
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                htmlDocumentInfo = JsoupTaskCallback.check(content);
                message.setHtmlDocumentInfo(htmlDocumentInfo);
            }
            showHtmlInfo(htmlDocumentInfo,message,helper);

            helper.setText(R.id.line_content,content);
        }else if(message.messageType==TelegramManager.MessageType.MessageType_Document){
            DocumentInfo documentInfo = message.content.document;
            if(documentInfo!=null){
                helper.setText(R.id.file_name_text, message.content.title);
                helper.setText(R.id.file_info_text,String.format("%s   %s", DocumentInfo.fileTypeIcon(documentInfo.file_name), TimeUtils.getMsgFormatHMTime(message.date*1000)));
            }
        }

    }

    private void showHtmlInfo(HtmlDocumentInfo documentInfo,MessageInfo messageInfo,BaseViewHolder helper){
        String imagePath = "";
        if(placeholderOptions == null){
            placeholderOptions = new RequestOptions();
            placeholderOptions.diskCacheStrategy(DiskCacheStrategy.ALL);
            placeholderOptions.centerCrop();
            placeholderOptions.placeholder(R.mipmap.group_setting_of_link);
        }

        if(documentInfo!=null){
            helper.setGone(R.id.file_info_text,false);
            imagePath = documentInfo.getIcon();
            helper.setText(R.id.file_name_text,documentInfo.getTitle());
            helper.setText(R.id.file_info_text,documentInfo.getContent());
        }else{
            helper.setText(R.id.file_name_text,HtmlDocumentInfo.checkUrl(messageInfo.textTypeContent));
            helper.setGone(R.id.file_info_text,true);
        }
        if(!TextUtils.isEmpty(imagePath)&&imagePath.endsWith(".svg")){
            Glide.with(getContext()).as(PictureDrawable.class)
                    .listener(new SvgSoftwareLayerSetter())
                    .load(imagePath).into((ImageView) helper.getView(R.id.file_icon));
            return;
        }
        Glide.with(getContext())
                .load(imagePath)
                .apply(placeholderOptions)
                .into((ImageView) helper.getView(R.id.file_icon));
    }

    @NonNull
    @Override
    public BaseLoadMoreModule addLoadMoreModule(@NonNull BaseQuickAdapter<?, ?> baseQuickAdapter) {
        return new BaseLoadMoreModule(baseQuickAdapter);
    }
}
